package com.theobserver.theobserver;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class SendNewsActivity extends AppCompatActivity {

    private ImageView mImageViewSelect;
    private byte[] mImagecover = null;
    private ArrayList<byte[]> mImageviews = null;
    private Handler mHandler = new Handler();
    private ProgressBar mProgerss;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sendnews);

        TextView mreturn = (TextView)findViewById(R.id.TextView_sendnews_return);
        mreturn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                finish();
            }
        });

        mImageViewSelect = (ImageView) findViewById(R.id.imageView_sendnews_cover);
        mProgerss = (ProgressBar) findViewById(R.id.mProgess);

        Button mButtonSelectCover = (Button) findViewById(R.id.button_sendnews_select);
        mButtonSelectCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View cover) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 42);
            }
        });


        final EditText mTitleEdit = (EditText) findViewById(R.id.EditText_sendnews_title);
        final EditText mDiscriptionEdit = (EditText) findViewById(R.id.TextView_sendnews_content);

        findViewById(R.id.button_sendnews_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("".equals(mTitleEdit.getText().toString())) {
                    Toast.makeText(SendNewsActivity.this, "输入标题", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("".equals(mDiscriptionEdit.getText().toString())) {
                    Toast.makeText(SendNewsActivity.this, "输入内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mImagecover == null) {
                    Toast.makeText(SendNewsActivity.this, "选择图片上传", Toast.LENGTH_SHORT).show();
                    return;
                }

                AVUser cur_user = AVUser.getCurrentUser();

                final AVObject catalog = AVObject.createWithoutData("catalog", "596731f7ac502e006c864a48");
                catalog.fetchInBackground(new GetCallback<AVObject>() {
                    @Override
                    public void done(AVObject avObject, AVException e) {
                        if(e == null)
                        {
                            final AVFile news_image = new AVFile("coverimage", mImagecover);

                            mProgerss.setVisibility(View.VISIBLE);
                            final AVObject news = new AVObject("news");
                            news.put("news_title", mTitleEdit.getText().toString());
                            news.put("news_content", mDiscriptionEdit.getText().toString());
                            news.put("news_reporter", AVUser.getCurrentUser());
                            news.put("news_cover", news_image);
                            news.put("news_type", 2);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            news.put("news_date", sdf.format(new Date()));
                            news.put("news_has_image", 1);
                            news.put("news_catalog", catalog);


                            news.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(AVException e) {
                                    if (e == null) {
                                        mProgerss.setVisibility(View.GONE);
                                        AVObject news_image_save = new AVObject("image");
                                        news_image_save.put("news_id", news);
                                        news_image_save.put("image_file", news_image);
                                        news_image_save.saveInBackground();
                                        SendNewsActivity.this.finish();
                                    } else {
                                        mProgerss.setVisibility(View.GONE);
                                        Toast.makeText(SendNewsActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    }
                });



                /*AVObject image = new AVObject("image");
                image.put("news_id",news);
                int n;
                n = mImageviews.size();
                for (;n>=0;n--){
                    image.put("news_image",new AVFile("viewimage",mImageviews.get(n)));
                }*/
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 42 && resultCode == RESULT_OK) {
            try {
                mImageViewSelect.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData()));
                mImagecover = getBytes(getContentResolver().openInputStream(data.getData()));
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        return byteArrayOutputStream.toByteArray();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //AVAnalytics.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //AVAnalytics.onResume(this);
    }
}
